import json
import os
import time
import requests


# 从文件中读取access_token
def get_access_token_from_file(filename):
    try:
        with open(filename, 'r') as file:
            data = json.load(file)
            if data.get('access_token') and data.get('expires_at'):
                if time.time() < data['expires_at']:
                    return data['access_token']
    except (FileNotFoundError, json.JSONDecodeError):
        print(FileNotFoundError)
        pass
    return None


# 保存访问令牌到文件中
def save_access_token_to_file(filename, access_token, expires_in):
    data = {
        'access_token': access_token,
        'expires_at': time.time() + expires_in
    }
    with open(filename, 'w') as file:
        json.dump(data, file)


# 获取访问令牌access_token
def get_access_token(corpid, corpsecret, filename):
    access_token = get_access_token_from_file(filename)
    if access_token:
        return access_token
    print(corpid, corpsecret, filename)
    url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={corpsecret}"
    response = requests.get(url)
    data = response.json()
    print(data)
    if data.get('access_token'):
        save_access_token_to_file(filename, data['access_token'], data['expires_in'])
        return data['access_token']
    else:
        return None


# 获取消息
def get_message(access_token, cursor, token, limit, voice_format, open_kfid):
    url = f"https://qyapi.weixin.qq.com/cgi-bin/kf/sync_msg?access_token={access_token}"
    data = {
        "cursor": cursor,
        "token": token,
        "limit": limit,
        "voice_format": voice_format,
        "open_kfid": open_kfid}

    response = requests.post(url, json=data)
    return response.json()


# 发送客服消息
def send_message_text(access_token, touser, open_kfid, msgid, content):
    url = f"https://qyapi.weixin.qq.com/cgi-bin/kf/send_msg?access_token={access_token}"
    data = {
        "touser": touser,
        "open_kfid": open_kfid,
        "msgid": msgid,
        "msgtype": "text",
        "text": {
            "content": content
        }
    }
    response = requests.post(url, json=data)
    return response.json()


# 发送单聊消息
def send_app_message_text(access_token, touser,agentid, content):
    url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}"
    data = {
        "touser": touser,
        "msgtype": "text",
        "agentid": agentid,
        "text": {
            "content": content
        },
        "safe": 0
    }
    response = requests.post(url, json=data)
    return response.json()


# 获取成员信息
def get_user_info(access_token, userid):
    url = f"https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={access_token}&userid={userid}"

    response = requests.get(url)
    data = response.json()
    return data

def decrypting_data(token, encoding_aes_key, nonce, timestamp, msg_signature, data):
    from wechatpy.crypto import WeChatCrypto
    crypto = WeChatCrypto(token, encoding_aes_key, 'wx195f7d1dc767e06a')
if __name__ == '__main__':
    print(get_access_token_from_file("../core/access_token.json"))
